package com.at.service.impl;


import com.at.dao.TypeDao;
import com.at.domain.Type;
import com.at.exception.NotFoundException;
import com.at.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author : code1997
 * @date :2020-09-2020/9/28 18:12
 */
@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private TypeDao typeDao;

    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeDao.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeDao.getOne(id);
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeDao.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeDao.findAll();
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        //,"blogs.size"
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size, sort);
        return typeDao.getTop(pageable);
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        //可以安全的判断对象是否存在，避免空的出现
        Optional<Type> byId = typeDao.findById(id);
        if (!byId.isPresent()){
            throw new NotFoundException("该类型不存在！更新失败！！！");
        }
        Type tempType = byId.get();
        System.out.println(tempType);
        //赋值
        BeanUtils.copyProperties(type , tempType);
        return typeDao.save(tempType);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeDao.deleteById(id);
    }

    @Transactional
    @Override
    public Type getTypeByName(String name) {
        return typeDao.getTypeByName(name);
    }
}
